<template>
  <div class="flex flex-col gap-2">
    <VueDraggable
      ref="dragContainer"
      v-model="coms"
      :animation="150"
      handle=".normal-class"
      class="w-full min-h-[300px] flex flex-col gap-2 relative"
      ghost-class="ghost-placeholder"
      drag-class="dragging-item"
      @dragenter.prevent="handleDragEnter"
      @dragleave.prevent="handleDragLeave"
      @end="handleDragEnd"
    >
      <template v-for="(com, index) in coms" :key="com.comsId">
        <div
          class="w-full h-10 flex items-center px-2 rounded-md border cursor-move"
          :class="dynamicClassName(com.comsId)"
        >
          <div class="flex items-center gap-2">
            <div
              class="text-xs text-white bg-[#7caeff] rounded-md px-2 py-1 text-nowrap"
            >
              {{ `${index + 1}.${com.comsName}` }}
            </div>
            <div
              class="text-sm text-gray-500 text-nowrap overflow-hidden text-ellipsis"
            >
              {{ com.comsTitle }}
            </div>
          </div>
        </div>
      </template>
    </VueDraggable>
  </div>
</template>

<script setup lang="ts">
import { VueDraggable } from "vue-draggable-plus";
import { useEditorStore } from "@/stores/useEditor";
import { getComNameByMaterialName } from "@/configs/SurveyGroupConfig";
import { useDragJudge } from "@/utils/drag";

const editorStore = useEditorStore();

interface IComs {
  comsId: string;
  comsName: string;
  comsTitle: string;
}

// * 获取所有组件的id、name、title
const coms = ref<IComs[]>(
  editorStore.coms.map((com) => {
    const comsId = com.id;
    const comsName = getComNameByMaterialName(com.name)!;
    const comsTitle = com.status.title.status;
    return {
      comsId,
      comsName,
      comsTitle,
    };
  }),
);

const dynamicClassName = (id: string) => {
  const staticItem = ["static-default-title", "static-default-desc"];

  return staticItem.includes(id) ? "static-class" : "normal-class";
};

// - 拖拽结束事件
const handleDragEnd = (e: any) => {
  console.log("拖拽结束", e, toRaw(coms.value), toRaw(editorStore.coms));
  const { oldIndex, newIndex } = e;

  const [item] = editorStore.coms.splice(oldIndex, 1);
  editorStore.coms.splice(newIndex, 0, item);
  // console.log(editorStore.coms);
};

// - 拖拽容器
const dragContainer = useTemplateRef<HTMLElement>("dragContainer");

const { handleDragEnter, handleDragLeave } = useDragJudge(dragContainer);

defineOptions({
  meta: {
    title: "大纲",
    __isRouteComponent: true,
    __parentPath: "/src/views/Editor/Editor.vue",
  },
});
</script>

<style scoped></style>
